<template>
  <div class="compensation-management-page">
    <!-- 申请赔偿按钮 -->
    <el-button type="primary" @click="onCompensationRequestClick">申请赔偿</el-button>

    <!-- 赔偿记录表格 -->
    <el-table :data="tableData" style="width: 100%; margin-top: 20px;">
      <el-table-column prop="driverId" label="司机ID" width="100"></el-table-column>
      <el-table-column prop="orderId" label="订单ID" width="200"></el-table-column>
      <el-table-column prop="goodsName" label="货物名称" width="150"></el-table-column>
      <el-table-column prop="level" label="损坏程度" width="120"></el-table-column>
      <el-table-column prop="money" label="赔偿金额" width="100"></el-table-column>
      <el-table-column prop="reason" label="赔偿原因" width="200"></el-table-column>
      <el-table-column prop="imageUrl" label="货物图片" width="150">
        <template #default="scope">
          <el-image
              style="width: 100px; height: 100px"
              :src="scope.row.imageUrl"
              fit="cover"
              lazy
          ></el-image>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="150"></el-table-column>
      <el-table-column fixed="right" label="操作" width="200">
        <template #default="scope">
          <el-button
              plain
              type="danger"
              size="small"
              @click="openCancelDialog(scope.row)"
              :disabled="scope.row.status === '已完成' || scope.row.status === '被驳回'"
          >
            取消赔偿
          </el-button>
          <el-button
              plain
              type="info"
              size="small"
              @click="viewProcessStatus(scope.row)"
              :disabled="!scope.row.processInstanceId"
          >
            查看流程
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 申请赔偿弹框 -->
    <el-dialog :title="modalTitle" v-model="dialogVisible" width="800px" center>
      <el-form :model="form" label-width="100px" :rules="rules" ref="compensationForm">
        <el-form-item label="订单 ID" prop="orderId">
          <el-input v-model="form.orderId" placeholder="请输入订单 ID" style="width: 100%;"></el-input>
        </el-form-item>
        <el-form-item label="货物名称" prop="goodsName">
          <el-input v-model="form.goodsName" placeholder="请输入货物名称" style="width: 100%;"></el-input>
        </el-form-item>
        <el-form-item label="损坏程度" prop="level">
          <el-input v-model="form.level" placeholder="请输入损坏程度" style="width: 100%;"></el-input>
        </el-form-item>
        <el-form-item label="赔偿原因" prop="reason">
          <el-input type="textarea" v-model="form.reason" placeholder="请输入赔偿原因" style="width: 100%;"></el-input>
        </el-form-item>
        <el-form-item label="上传图片" prop="imageUrl">
          <el-upload
              class="upload-demo"
              :http-request="customHttpRequest"
              :before-upload="beforeUpload"
              :file-list="form.imageList"
              list-type="picture-card"
              :limit="1"
              auto-upload
          >
            <i class="el-icon-plus"></i>
          </el-upload>
          <div v-if="form.imageUrl" style="margin-top: 10px;">
            <img :src="form.imageUrl" alt="Uploaded Image" style="width: 100px; height: 100px; object-fit: cover;"/>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="onSubmit">提交</el-button>
      </div>
    </el-dialog>

    <!-- 取消赔偿的弹框 -->
    <el-dialog title="取消赔偿" v-model="cancelDialogVisible" width="400px" center>
      <el-input type="textarea" v-model="cancelReason" placeholder="请输入取消赔偿原因"></el-input>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitCancelCompensation">提交</el-button>
      </div>
    </el-dialog>

    <!-- 查看流程弹框 -->
    <el-dialog title="赔偿流程状态" v-model="processStatusDialogVisible" width="600px" center>
      <el-timeline>
        <el-timeline-item
            v-for="(step, index) in processStatus"
            :key="index"
            :timestamp="step.timestamp"
            :color="step.completed ? 'green' : 'gray'"
        >
          {{ step.name }} ({{ step.completed ? '已完成' : '未完成' }}) - {{
            step.completed
                ? (step.agreeResult === 'N' ? '驳回' : '通过')
                : '未通过'
          }}
        </el-timeline-item>
      </el-timeline>
      <div slot="footer" class="dialog-footer">
        <el-button @click="processStatusDialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios';
import moment from 'moment';
import {ElMessage} from 'element-plus';

export default {
  name: 'CompensationManagement',
  data() {
    return {
      tableData: [],
      form: {
        orderId: '',
        goodsName: '',
        level: '', // '10%' or '20%'
        reason: '',
        imageList: [], // 用于el-upload的文件列表
        imageUrl: '', // 上传成功后的图片URL
      },
      modalTitle: '申请赔偿',
      dialogVisible: false,
      cancelDialogVisible: false,
      cancelReason: '',
      selectedProcessInstanceId: '',
      processStatusDialogVisible: false,
      processStatus: [],
      rules: {
        orderId: [
          {required: true, message: '请输入订单 ID', trigger: 'blur'},
        ],
        goodsName: [
          {required: true, message: '请输入货物名称', trigger: 'blur'},
        ],
        level: [
          {required: true, message: '请选择损坏程度', trigger: 'change'},
        ],
        reason: [
          {required: true, message: '请输入赔偿原因', trigger: 'blur'},
        ],
        imageUrl: [
          {required: true, message: '请上传图片', trigger: 'blur'},
        ],
      },
    };
  },
  mounted() {
    this.fetchData();
  },
  methods: {
    fetchData() {
      axios.get('/compensation/findHistoryById').then(res => {
        this.tableData = res.data.data.map(item => {
          const firstTask = item.customTaskList[0];
          const isRejected = item.customTaskList.some(task => task.details.auditResult === 'N'); // 检查是否被驳回

          return {
            driverId: firstTask.details.compensation?.driverId,
            orderId: firstTask.details.compensation?.orderId,
            goodsName: firstTask.details.compensation?.goodsName,
            level: firstTask.details.compensation?.level,
            money: firstTask.details.compensation?.money,
            reason: firstTask.details.compensation?.reason,
            imageUrl: firstTask.details.compensation?.url,
            // 状态：被驳回、已完成、进行中
            status: isRejected
                ? '被驳回'
                : item.finished ? '已完成' : '进行中',
            processInstanceId: firstTask.processInstanceId,
            customTaskList: item.customTaskList, // 保存流程信息以便后续使用
          };
        });
      });
    },

    onCompensationRequestClick() {
      this.modalTitle = '申请赔偿';
      this.resetForm();
      this.dialogVisible = true;
    },

    customHttpRequest({file}) {
      const formData = new FormData();
      formData.append('file', file);

      axios.post('/sys/user/uploadAvatar', formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
          'authorization': localStorage.getItem('token') // 示例：添加 Authorization 头
        }
      }).then(response => {
        if (response.data.code === 200) {
          this.form.imageUrl = response.data.data; // 假设 data 返回的是图片URL

          // 触发图片验证
          this.$refs.compensationForm.validateField('imageUrl');

          ElMessage({
            message: '图片上传成功',
            type: 'success',
            duration: 2000,
          });
        } else {
          ElMessage({
            message: '图片上传失败',
            type: 'error',
            duration: 2000,
          });
        }
      }).catch(() => {
        ElMessage({
          message: '图片上传失败，请稍后重试。',
          type: 'error',
          duration: 2000,
        });
      });
    },

    beforeUpload(file) {
      const isImage = file.type.startsWith('image/');
      if (!isImage) {
        ElMessage.error('只能上传图片文件');
      }
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        ElMessage.error('图片大小不能超过 2MB!');
      }
      return isImage && isLt2M;
    },

    onSubmit() {
      this.$refs.compensationForm.validate((valid) => {
        if (valid) {
          // 先通过 orderId 获取 orderItems
          const orderNo = this.form.orderId;
          axios.get(`/orderItem/findByOrderNo/${orderNo}`).then((response) => {
            const orderItems = response.data.data; // 假设返回的数据是一个数组

            // 然后发送 compensation 请求
            const compensation = {
              orderId: this.form.orderId,
              goodsName: this.form.goodsName,
              level: this.form.level,
              reason: this.form.reason,
              url: this.form.imageUrl,
              orderItems: orderItems // 将 orderItems 加入请求体
            };
            console.log(compensation)

            axios.post('/compensation/apply', compensation).then((res) => {
              if (res.data.code === 200) {
                this.dialogVisible = false;
                this.resetForm();
                ElMessage({
                  message: '提交赔偿申请成功，等待审核。',
                  type: 'success',
                  duration: 3000,
                });
                this.fetchData();
              } else {
                ElMessage({
                  message: '提交赔偿申请失败，请重新提交。',
                  type: 'error',
                  duration: 3000,
                });
              }
            }).catch(() => {
              ElMessage({
                message: '网络错误，请稍后再试。',
                type: 'error',
                duration: 3000,
              });
            });

          }).catch(() => {
            ElMessage({
              message: '获取订单项失败，请稍后再试。',
              type: 'error',
              duration: 3000,
            });
          });
        } else {
          ElMessage({
            message: '请完善表单信息。',
            type: 'warning',
            duration: 3000,
          });
          return false;
        }
      });
    },

    resetForm() {
      this.form = {
        orderId: '',
        goodsName: '',
        level: '',
        reason: '',
        imageList: [],
        imageUrl: '',
      };
      if (this.$refs.compensationForm) {
        this.$refs.compensationForm.resetFields();
      }
    },

    openCancelDialog(row) {
      if (row.status !== '已完成') {
        this.selectedProcessInstanceId = row.processInstanceId;
        this.cancelDialogVisible = true;
      }
    },

    submitCancelCompensation() {
      if (!this.cancelReason) {
        ElMessage({
          message: '请输入取消原因',
          type: 'warning',
          duration: 2000,
        });
        return;
      }
      axios.post('/compensation/cancel', {
        pid: this.selectedProcessInstanceId,
        reason: this.cancelReason,
      }).then(res => {
        if (res.data.code === 200) {
          ElMessage({
            message: '取消赔偿申请成功',
            type: 'success',
            duration: 3000,
          });
          this.cancelDialogVisible = false;
          this.cancelReason = '';
          this.fetchData();
        } else {
          ElMessage({
            message: '取消赔偿申请失败，请重试',
            type: 'error',
            duration: 3000,
          });
        }
      }).catch(() => {
        ElMessage({
          message: '网络错误，请稍后再试。',
          type: 'error',
          duration: 3000,
        });
      });
    },

    viewProcessStatus(row) {
      axios.get(`/compensation/getProcessStatus/${row.processInstanceId}`).then(res => {
        console.log(res.data.data)
        if (res.data.code === 200) {
          this.processStatus = res.data.data.map(step => ({
            name: step.name,
            timestamp: moment(step.timestamp).format('YYYY-MM-DD HH:mm:ss'),
            completed: step.completed,
            agreeResult: step.agreeResult
          }));
          this.processStatusDialogVisible = true;
        } else {
          ElMessage({
            message: '获取流程状态失败，请重试',
            type: 'error',
            duration: 3000,
          });
        }
      }).catch(() => {
        ElMessage({
          message: '网络错误，请稍后再试。',
          type: 'error',
          duration: 3000,
        });
      });
    }
  },
};
</script>

<style scoped>
.compensation-management-page {
  padding: 20px;
}

.dialog-footer {
  text-align: right;
}

:deep(.el-dialog) {
  position: fixed !important;
  top: 50% !important;
  left: 50% !important;
  transform: translate(-50%, -50%) !important;
  max-width: 90% !important;
  max-height: 80vh !important;
}

:deep(.el-dialog__body) {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

:deep(.el-dialog__header) {
  text-align: center;
}

:deep(.el-dialog__body .el-form) {
  width: 100%;
}

:deep(.el-dialog__body .el-form-item) {
  margin-bottom: 20px;
}
</style>
